package com.mybatis.study;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import com.mybatis.study.model.FieldAndType;

public class ReflectionUtil {

	public static Map<String, String> javaTypeMap = new HashMap<String, String>();

	static {
		javaTypeMap.put("tinyint", "Integer");
		javaTypeMap.put("smallint", "Integer");
		javaTypeMap.put("mediumint", "Integer");
		javaTypeMap.put("int", "Integer");
		javaTypeMap.put("integer", "integer");
		javaTypeMap.put("bigint", "Long");
		javaTypeMap.put("float", "Float");
		javaTypeMap.put("double", "Double");
		javaTypeMap.put("decimal", "BigDecimal");
		javaTypeMap.put("bit", "Boolean");
		javaTypeMap.put("char", "String");
		javaTypeMap.put("varchar", "String");
		javaTypeMap.put("tinytext", "String");
		javaTypeMap.put("text", "String");
		javaTypeMap.put("mediumtext", "String");
		javaTypeMap.put("longtext", "String");
		javaTypeMap.put("time", "Date");
		javaTypeMap.put("date", "Date");
		javaTypeMap.put("datetime", "Date");
		javaTypeMap.put("timestamp", "Date");
	}

	public static void setProPtoBeanFromResultSet(Object entity, ResultSet set, Map<String, FieldAndType> param)
			throws SQLException {
		Field[] declFields = entity.getClass().getDeclaredFields(); // 反射获取全部字段
		for (int i = 0; i < declFields.length; i++) {// 遍历字段，分别去set里面找对应的值
			if(param==null) {
				setProToBean(entity, declFields[i].getName(), set.getObject(declFields[i].getName()));
			}else {
				setProToBean(entity, declFields[i].getName(), set.getObject(param.get(declFields[i].getName()).getField()));
			}
		}

	}

	public static void setProToBean(Object bean, String propName, Object value) {
		Field f;
		try {
			f = bean.getClass().getDeclaredField(propName);
			f.setAccessible(true); // 该字段可以通过反射访问
			try {
				f.set(bean, value); // 为属性设值
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (NoSuchFieldException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void main(String[] args)
			throws ClassNotFoundException, InstantiationException, IllegalAccessException {
		Class clazz = Class.forName("com.mybatis.study.model.User");
		Object user = clazz.newInstance();
		ReflectionUtil.setProToBean(user, "username", "哈哈");
		System.out.println(user);
	}
}
